package com.wanshi.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wanshi.entity.Result;
import com.wanshi.entity.User;
import com.wanshi.service.IUserService;

import com.wanshi.utils.DateUtils;
import com.wanshi.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 顽石教育-www.wanshi.com
 * @since 2021-12-08
 */
//跨域
@CrossOrigin
@RestController
@RequestMapping("/user")
//@PropertySource("classpath:cust.properties")
public class UserController {

    @Autowired
    private IUserService userService;

   /* @Value("${pic_save_path}")
    private String picSavePath;

    @Value("${pic_url}")
    private  String picUrl;
*/

    @GetMapping("/list")
    public Result list(){
        return Result.ok(userService.list());
    }


    //根据id查询
    @GetMapping("/{id}")
    public Result findById(@PathVariable String id){
       return Result.ok(userService.getById(id));
    }


    //添加 注册
/*    @PostMapping
    public String addCust(@RequestBody User user){

        userService.save(user);
        System.out.println("--------"+user.getId());
        return "添加成功";
    }*/

   /* @PostMapping("/regist")
    public String regist(MultipartFile touxiang, HttpSession session, String yan, Model model, User user) throws IOException {

       *//* String ma = (String) session.getAttribute("ma");
        if (ma == null || !ma.equals(yan)) {
            model.addAttribute("error", "验证码错误");
            model.addAttribute("user", user);
            return "regist";
        }*//*

        String name = touxiang.getOriginalFilename();
        //判断用户是否上传了图片
        if (name.length() > 0) {
            String s = UUID.randomUUID().toString().replace("-", "");
            //获取文件名称后缀
            int index = name.lastIndexOf('.');
            String houzhui = name.substring(index);

            String date = DateUtils.getFormatDate();  //    2021/11/02/
            File file = new File(picSavePath + date);
            if (!file.exists()) {
                file.mkdirs();
            }
            File fileName = new File(file, s + houzhui);
            touxiang.transferTo(fileName);
            user.setPicurl(date + s + houzhui);
        }


       *//* Map<String, String> errorMap = user.checkUser();
        if (errorMap.size() > 0) {
            model.addAttribute("map", errorMap);
            model.addAttribute("user", user);
            return "regist";
        }*//*
        user.setPassword(MD5Util.getMD5Str(user.getPassword()));

      *//*  if (!StringUtils.isEmpty(user.getUsername())){
            model.addAttribute("error", "该用户名已经存在!");
            model.addAttribute("user", user);
            return "regist";
        } else {*//*
        boolean save = userService.save(user);
        if (save){
            return "注册成功";
        }else {
            return "注册失败";
        }

    }*/

    //根据用户名和密码查询
    @GetMapping("/find/{password}/{username}")
    public Result findByNameAndPsd(@PathVariable String username,
                                   @PathVariable String password){

        QueryWrapper<User> wraper = new QueryWrapper<>();
        wraper.eq("username",username);
        wraper.eq("password",password);
        return Result.ok(userService.getOne(wraper));
    }


    //根据姓名模糊查询
    @GetMapping("/name/{useranme}")
    public List findByName(@PathVariable String useranme){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("useranme",useranme);
        return userService.list(wrapper);
    }

    //分页查询
    @GetMapping("/page/{ye}/{size}")
    public Result findByPage(@PathVariable int ye , @PathVariable int size){
        Page<User> page = new Page<>(ye,size);
        userService.page(page);
        return Result.ok(page);

    }

    //批量查询
    @GetMapping("/ids")
    public List findByIds(@PathVariable List<String> ids){
        return userService.listByIds(ids);
    }

    //条件查询
    @GetMapping("/cond")
    public List cond(@RequestBody User user){

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(user.getId())){
            wrapper.eq("id",user.getId());
        }
        if (!StringUtils.isEmpty(user.getUsername())){
            wrapper.like("username",user.getUsername());
        }
        if (!StringUtils.isEmpty(user.getGender())){
            wrapper.eq("gender",user.getGender());
        }
        if (!StringUtils.isEmpty(user.getCity())){
            wrapper.eq("city",user.getCity());
        }
        return userService.list(wrapper);
    }

    //待条件的分页
    //{username:"zhangsan"}

    @PostMapping("/findByPageandCond/{ye}/{size}")
    public Result findByPageandCond(@PathVariable int ye , @PathVariable int size, @RequestBody User user){
        Page<User> page = new Page<>(ye,size);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(user.getUsername())){
            wrapper.like("username",user.getUsername());
        }
        if (!StringUtils.isEmpty(user.getGender())){
            wrapper.eq("gender",user.getGender());
        }
        if (!StringUtils.isEmpty(user.getCity())){
            wrapper.eq("city",user.getCity());
        }
        wrapper.orderByDesc("id");
        userService.page(page,wrapper);
        return Result.ok(page);

    }

 @PostMapping("/login")
    private String login(User user, Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
       // wrapper.like("useranme",username);
        wrapper.in("username",user.getUsername());
        user.setPassword(MD5Util.getMD5Str(user.getPassword()));
        wrapper.in("password",user.getPassword());
     User one = userService.getOne(wrapper);
     if(one == null){
          return "登录失败";
        }else{
         session.setAttribute("user",one);
          return "登陆成功";
        }
    }


    //删除用户

    @DeleteMapping("/{id}")
    public Result delUser(@PathVariable String id){

     userService.removeById(id);

     return Result.ok();
    }

    //修改用户
    @PutMapping
    public Result update(@RequestBody User user){
        userService.updateById(user);
        return Result.ok();
    }

    //新增用户
    @PostMapping
    public Result addUser(@RequestBody User user){
        if(StringUtils.isEmpty(user.getPassword())){
            user.setPassword("33333");
        }
        userService.saveOrUpdate(user);
        return Result.ok();

    }

//批量删除用户

    @PostMapping("/batch")
    public Result delBatch(@RequestBody List<String> ids){
        userService.removeByIds(ids);
        return Result.ok();
    }


}

